package com.prs.crm.dao.sys.impl;
import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.sys.CodeCommonDao;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.domain.sys.CodeInvoice;


public class CodeCommonDaoImpl extends BaseDaoImpl<CodeCommon> implements
		CodeCommonDao {
	
	@SuppressWarnings("unchecked")
	@Override
	public List<CodeCommon> getCodeCommonByCodeType(final String type) {
		return (List<CodeCommon>) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Criteria criteria = session
								.createCriteria(CodeCommon.class);
						//criteria.add(Restrictions.eq("codeState", 0));
						criteria.add(Restrictions.eq("codeType", type));
						return criteria.list();
					}
				});
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	 public int getCodeCommonCodeName(final String name) {
		
		return (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Criteria criteria = session.createCriteria(CodeCommon.class);
						criteria.add(Restrictions.eq("codePlan", name));
						return criteria.list().size();
					}
				});
	}

	@Override
	public CodeCommon getVobject(Serializable id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(CodeCommon.class, id);
	}

	@Override
	public void saveOrUpdate(CodeCommon codeCommon) {
		int numbackUp=Integer.parseInt(codeCommon.getNumBackUp());
		int codeNumber=Integer.parseInt(codeCommon.getCodeNumber());
		String a="";
		for(int i=0;i<codeNumber;i++){
			a=a+"9";
		}
		int num=Integer.parseInt(a);
		if(num<numbackUp){
			codeCommon.setCodeState(1);
		}
		this.getHibernateTemplate().saveOrUpdate(codeCommon);
	}


	@Override
	public void deleteCode(CodeCommon codeCommon) {
		//this.getHibernateTemplate().delete(codeCommon);
		this.getHibernateTemplate().delete(codeCommon);
	}

	
	

}
